﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using MySql.Data.MySqlClient;
using System.Reflection;
using Common.Expansion;
using System.Configuration;

namespace Common
{
    public class Utility
    {
        public static MySqlParameter[] CreateParameters(Dictionary<string, object> dict)
        {
            List<MySqlParameter> list = new List<MySqlParameter>();
            foreach (KeyValuePair<string, object> item in dict)
                list.Add(new MySqlParameter(item.Key, item.Value));
            return list.ToArray();
        }

        public static string InsertString(EntityObject entity)
        {
            Type t = entity.GetType();
            PropertyInfo[] info = t.GetProperties();

            List<string> field = new List<string>();
            List<string> value = new List<string>();

            for (int i = 0; i < info.Length; i++)
            {
                if (info[i].Name == "EntityState"
                    || info[i].Name == "EntityKey"
                    || info[i].GetValue(entity, null).TryInt() == AppConst.PRIMARY_KEY)
                    continue;

                field.Add(info[i].Name);
                value.Add("'" + info[i].GetValue(entity, null) + "'");
            }

            return string.Format("insert into {0}({1}) values({2})",
                t.Name, string.Join(",", field), string.Join(",", value));
        }

        public static string FormatString(string str)
        {
            str = str.Replace("<", "[");
            str = str.Replace(">", "[");
            str = str.Replace("script", "sc..t");
            str = str.Replace("asp", "a_p");
            return str;
        }

        public static void SetAppConfig(string key, string value)
        {
            Configuration webconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            webconfig.AppSettings.Settings[key].Value = value;
            webconfig.Save(ConfigurationSaveMode.Modified);
        }


    }
}
